package com.pai.service;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException;

import com.pai.util.PropertiesUtil;

/**
 * 用于多播的服务。能在特定网段广播，但是需要多播路由器的支持。代码实现完毕但是未使用到。
 * @author Jeff
 *
 */
public class MulticastService {

	public static MulticastService myService = new MulticastService();
	private int port;
	private InetAddress multicastAddress;
	public MulticastService(){
		PropertiesUtil propertieUtil = new PropertiesUtil();
		propertieUtil.loadPropertyFile("src/config.properties");
		
		try {
			this.multicastAddress = InetAddress.getByName(propertieUtil.getProperty("multicast_address"));
			this.port = Integer.parseInt(propertieUtil.getProperty("port"));
		} catch (NumberFormatException e) {
			throw new IllegalArgumentException("端口号设置错误，请输入整数的端口号。");
		} catch (UnknownHostException e) {
			throw new IllegalArgumentException("多播地址设置错误。请输入正确的(符合条件的)ip地址");
		}
		
	}
	/**
	 * 发送多播的报文
	 * @param message 发送信息
	 * @throws IOException
	 */
	public void sendMessage(String message) throws IOException{
		 MulticastSocket multicastSocket = new MulticastSocket();
		//TODO: 此处可能需要对中文进行处理防止乱码
        DatagramPacket datagramPacket = new DatagramPacket(message.getBytes(), message.length(), multicastAddress, port);
        multicastSocket.send(datagramPacket);
        multicastSocket.close();
	}
	
	/**
	 * 接收报文
	 * @throws IOException
	 */
	public void receiveMessage() throws IOException{
		final MulticastSocket s = new MulticastSocket(port);
		final byte[] arb = new byte[1024];
		s.joinGroup(multicastAddress);//加入该组  
		Thread thread = new Thread(new Runnable() {
			
			@Override
			public void run() {
				while(true){
					DatagramPacket datagramPacket =new DatagramPacket(arb,arb.length);  
					try {
						s.receive(datagramPacket);
					} catch (IOException e) {
						e.printStackTrace();
					} 
	                 System.out.println(arb.length);  
	                 System.out.println(new String(arb)); 
	                 System.out.println(datagramPacket.getAddress()+":"+datagramPacket.getPort());
				}
				
			}
		});
		
		thread.start();
	}
	
}
